package com.franklin.java.api.psi.comment;

import com.franklin.plugins.common.collection.PrettyArrayList;
import com.franklin.plugins.common.utils.DataCheckUtils;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author Franklin
 * @since 2021/9/2 14:40
 */
class PsiFieldCommentResolver extends AbstractPsiCommentResolver<PsiField> {
    @Override
    public String resolveComment(PsiField psiField) {
        List<PsiComment> psiComments = PsiTreeUtil.getChildrenOfTypeAsList(psiField, PsiComment.class);
        if (DataCheckUtils.isEmpty(psiComments)){
            return "";
        }
        List<String> commentTextList = new PrettyArrayList<>();
        for (PsiComment psiComment : psiComments) {
            if (psiComment instanceof PsiDocComment){
                /**
                 * java doc
                 */
                PsiDocComment psiDocComment = (PsiDocComment) psiComment;
                PsiElement[] descriptionElements = psiDocComment.getDescriptionElements();
                for (PsiElement descriptionElement : descriptionElements) {
                    String text = descriptionElement.getText();
                    if (StringUtils.isNotBlank(text)){
                        commentTextList.add(text.trim());
                    }
                }
            }else{
                String psiCommentText = psiComment.getText();
                if (psiCommentText.startsWith("//")){
                    //
                    int length = psiCommentText.length();
                    int index = 0;
                    for (int i = 0; i < length; i++) {
                        if (psiCommentText.charAt(i) != '/'){
                            index = i;
                            break;
                        }
                    }
                    commentTextList.add(psiCommentText.substring(index).trim());
                }else {
                    /*

                     */
                    psiCommentText = StringUtils.removeStart(psiCommentText,"/*");
                    psiCommentText = StringUtils.removeEnd(psiCommentText,"*/");
                    commentTextList.add(psiCommentText.trim());
                }
            }
        }
        if (DataCheckUtils.isNotEmpty(commentTextList)){
            return String.join(";",commentTextList);
        }
        return "";
    }

    @Override
    public String resolveSimpleComment(PsiField psiField) {
        return resolveComment(psiField);
    }
}
